import { BrowserWindow, Menu, MenuItem, MenuItemConstructorOptions, dialog, shell } from 'electron'
import fs from 'fs/promises'
import path from 'path'
import { FileItem } from '../types'
// 系统菜单
const createMenu = (mainWindow: BrowserWindow): void => {
  const menuTemplate: (MenuItemConstructorOptions | MenuItem)[] = [
    {
      label: '文件',
      submenu: [
        {
          label: '新建',
          accelerator: 'CmdOrCtrl+N',
          click: async () => {
            const { canceled, filePath } = await dialog.showSaveDialog({
              filters: [
                {
                  name: 'Markdown Files',
                  extensions: ['md']
                }
              ]
            })
            if (!canceled) {
              try {
                await fs.writeFile(filePath, '')
                mainWindow.webContents.send('open-file', {
                  content: '',
                  filePath: filePath,
                  fileName: path.basename(filePath)
                })
              } catch (error) {
                console.error('创建文件时出错:', error)
              }
            }
          }
        },
        { type: 'separator' },
        {
          label: '打开文件',
          accelerator: 'CmdOrCtrl+O',
          click: async () => {
            const { canceled, filePaths } = await dialog.showOpenDialog(mainWindow, {
              filters: [{ name: 'Markdown Files', extensions: ['md', 'markdown'] }],
              properties: ['openFile']
            })
            if (!canceled) {
              const content = await fs.readFile(filePaths[0], 'utf-8')
              mainWindow.webContents.send('open-file', {
                content,
                filePath: filePaths[0],
                fileName: path.basename(filePaths[0])
              })
            }
            return null
          }
        },
        {
          label: '打开文件夹',
          accelerator: 'CmdOrCtrl+K',
          click: async () => {
            const { canceled, filePaths } = await dialog.showOpenDialog(mainWindow, {
              properties: ['openDirectory']
            })
            if (!canceled) {
              const folderPath = filePaths[0]
              try {
                const files = await fs.readdir(folderPath)
                const mdFiles = files.filter((file) =>
                  ['.md', '.markdown'].includes(path.extname(file))
                )
                const fileList: FileItem[] = []
                for (const mdFile of mdFiles) {
                  const filePath = path.join(folderPath, mdFile)
                  const content = await fs.readFile(filePath, 'utf-8')
                  fileList.push({
                    content,
                    filePath,
                    fileName: mdFile
                  })
                }
                mainWindow.webContents.send('open-dir', fileList)
                mainWindow.webContents.send('open-file', fileList[0])
              } catch (error) {
                console.error('读取文件夹失败:', error)
              }
            }
            return null
          }
        },
        { type: 'separator' },
        {
          label: '保存',
          accelerator: 'CmdOrCtrl+S',
          click: () => {
            mainWindow.webContents.send('save-file')
          }
        },
        { type: 'separator' },
        {
          label: '退出',
          role: 'quit'
        }
      ]
    }
  ]
  const menu: Menu = Menu.buildFromTemplate(menuTemplate)
  Menu.setApplicationMenu(menu)
}
// 右键菜单
const createContextMenu = (mainWindow: BrowserWindow, filePath: string): void => {
  const template = [
    {
      label: '重命名',
      click: async () => {
        mainWindow.webContents.send('do-rename-file', filePath)
      }
    },
    { type: 'separator' }, // 添加分割线
    {
      label: '移除',
      click: async () => {
        mainWindow.webContents.send('removeOut-fileList', filePath)
      }
    },
    {
      label: '清空文件列表',
      click: async () => {
        mainWindow.webContents.send('clear-fileList')
      }
    },
    { type: 'separator' }, // 添加分割线
    {
      label: '打开所在目录',
      click: async () => {
        shell.openPath(path.dirname(filePath))
      }
    },
    { type: 'separator' }, // 添加分割线
    {
      label: '删除',
      click: async () => {
        try {
          // 显示确认对话框
          const { response } = await dialog.showMessageBox(mainWindow, {
            type: 'question',
            buttons: ['确定', '取消'],
            title: '确认删除',
            message: `确定要删除文件 ${path.basename(filePath)} 吗？`
          })
          if (response === 0) {
            // 用户点击确定，删除本地文件
            await fs.unlink(filePath)
            // 通知渲染进程，将文件从列表中移除
            mainWindow.webContents.send('removeOut-fileList', filePath)
          }
        } catch {
          dialog.showMessageBox(mainWindow, {
            type: 'error',
            title: '删除失败',
            message: `删除文件 ${path.basename(filePath)} 时出错，请稍后重试。`
          })
        }
      }
    }
  ]
  const menu = Menu.buildFromTemplate(template as MenuItemConstructorOptions[])
  menu.popup({ window: mainWindow })
}
export { createMenu, createContextMenu }
